import os
import io
from pymongo import MongoClient
img_path = 'E:\\image_pi_new_p2\\'

client = MongoClient(port=27017)
db=client['tiktok_p2']
from google.oauth2 import service_account
from google.cloud import vision
credentials = service_account.Credentials.from_service_account_file('D:\\steel-cairn-344600-a9938c7de2a7.json')

client = vision.ImageAnnotatorClient(credentials=credentials )
collistt=['happyhalloween','nativefamily','guitartok','isthisavailable','winterfashion','marchmadness','halloweenishere','stylehacks','baseballtiktok','weirdpets','thriftflip','colddays','gettheretogether']
#for col in db.list_collection_names()[250:297]:
for col in collistt:
    for obj in db[col].find():
        for i in range(10):
            if len(obj['frame_level']['f'+str(i)]['img'])>0 and (type(obj['frame_level']['f'+str(i)]['text'])is dict):
                file_name = os.path.abspath('E:\\image_pi_new_p2\\'+obj['_id']+'_'+str(i)+'.jpg')
                with io.open(file_name, 'rb') as image_file:
                    content = image_file.read()
                image = vision.Image(content=content)
                response = client.text_detection(image=image)
                texts = response.text_annotations
                if response.error.message:
                    raise Exception(
                        '{}\nFor more info on error messages, check: '
                        'https://cloud.google.com/apis/design/errors'.format(
                            response.error.message))
                    exit
                if len(texts)==0:
                    db[col].update_one({'_id': obj['_id']},
                                       {'$set': {'frame_level.f' + str(i) + '.text': ''}})
                else:
                    db[col].update_one({'_id': obj['_id']},
                                       {'$set': {'frame_level.f' + str(i) + '.text': texts[0].description}})
                print('update success ',col,obj['_id'],i)

